package com.yf.exam.modules.sys.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yf.exam.core.api.ApiRest;
import com.yf.exam.core.api.controller.BaseController;
import com.yf.exam.core.api.dto.PagingReqDTO;
import com.yf.exam.modules.paper.entity.Paper;
import com.yf.exam.modules.paper.service.PaperService;
import com.yf.exam.modules.qu.dto.request.QuQueryReqDTO;
import com.yf.exam.modules.sys.user.dto.UserDto;
import com.yf.exam.modules.sys.user.entity.SysUser;
import com.yf.exam.modules.sys.user.entity.TimeCount;
import com.yf.exam.modules.sys.user.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/exam/api/sys/user")
public class InfoController extends BaseController {
    @Autowired
    private PaperService paperService;
    @Autowired
    private SysUserService sysUserService;

    @PostMapping("/page")
    public ApiRest<Page<UserDto>> page(@RequestBody PagingReqDTO reqDTO){
        Page<Paper> pageInfo = new Page<>(reqDTO.getCurrent(),reqDTO.getSize());
        Page<UserDto> userDtoPage = new Page<>();

        LambdaQueryWrapper<Paper> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Paper::getUserScore);
        //将满足queryWrapper的数据封装给pageInfo
        paperService.page(pageInfo,queryWrapper);
        BeanUtils.copyProperties(pageInfo,userDtoPage,"records");
        List<Paper> records = pageInfo.getRecords();//获取pageInfo的各条数据信息

        List<UserDto> list = records.stream().map((item)->{
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(item,userDto);
            String userId = item.getUserId();
            SysUser sysUser = sysUserService.getById(userId);
            String userName = sysUser.getUserName();
            userDto.setUserName(userName);
            long end = item.getUpdateTime().getTime();
            log.info("当前时间转化成秒{}",end);
            long start = item.getCreateTime().getTime();
            log.info("================={}",start);
            Date date = new Date();
            date.setTime(end - start);
            log.info("所用时间+++++{}" ,date);
            userDto.setTime(date);
            return userDto;
        }).collect(Collectors.toList());
        userDtoPage.setRecords(list);
        ApiRest<Page> apiRest =new ApiRest<>();
        apiRest.setData(userDtoPage);
        return super.success(userDtoPage);
    }


    /**
     * 通过id获取用户考试信息
     * @param
     * @return
     */
    @PostMapping("/exam")
    public ApiRest<Page<Paper>> info(@RequestBody PagingReqDTO reqDTO){
        Page<Paper> pageInfo = new Page<>(reqDTO.getCurrent(),reqDTO.getSize());
        LambdaQueryWrapper<Paper> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Paper::getUserId,reqDTO.getUserId());
        wrapper.orderByAsc(Paper::getUpdateTime);
        paperService.page(pageInfo,wrapper);
        ApiRest<Page> apiRest =new ApiRest<>();
        apiRest.setData(pageInfo);
        return super.success(pageInfo);
    }
    @ResponseBody
    @PostMapping("/exam_frequency")
    public ApiRest<TimeCount> select_count(@RequestBody Paper paper){
        String userId = paper.getUserId();
        LambdaQueryWrapper<Paper> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Paper::getUserId, userId);
        List<Paper> list = paperService.list(queryWrapper);
        Date createTime = null;

        int times_Today = 0; //本日考试的次数
        int times_month = 0; //本月考试次数
        int time_year = 0;  //本年考试次数
        int Total_day = 0; //获取本年的总天数

        Calendar calendar = Calendar.getInstance();
        for(Paper paper1 : list){
            createTime = paper1.getCreateTime();//获取创建的时间

            Date d=new Date(); //获取当前时间
            int day = calendar.get(Calendar.DATE);
            int month = calendar.get(Calendar.MONTH) + 1;
            int year = calendar.get(Calendar.YEAR);
            for (int i = 1; i < month+1;i++){
                int sum = getMoneyDay(year,i);
                Total_day += sum;
            }
            Total_day += day;
//            SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
//            System.out.println("今天的日期："+df.format(d));
            Long time = new Date(d.getTime()-createTime.getTime()).getTime();
            long l = time/1000/60/60;//距今多少小时
            if(l < 24){
                times_Today++;
            }
            if(l < day * 24){
                times_month ++;
            }

            if (l < month * Total_day * 24){
                time_year++;
            }

//            System.out.println(new Date(d.getTime()-createTime.getTime()).getTime());
//            System.out.println("两天前的日期：" + df.format(new Date(d.getTime() - createTime.getTime())));
//            System.out.println("三天后的日期：" + df.format(new Date(d.getTime() + (long)3 * 24 * 60 * 60 * 1000)));
        }
        TimeCount timeCount = new TimeCount();
        timeCount.setDayCount(times_Today);
        timeCount.setMonthCount(times_month);
        timeCount.setYearCount(time_year);
        return super.success(timeCount);
    }
    public static int getMoneyDay(int year , int month)
    {
        Calendar a = Calendar.getInstance();//获取当前时间
        a.set(Calendar.YEAR, year );
        a.set(Calendar.MONTH, month-1);// Calendar月份是以0开始的 所以要-1
        a.set(Calendar.DATE, 1);//把日期设置为当月第一天
        a.roll(Calendar.DATE, -1);//日期回滚一天，也就是最后一天
        int day= a.get(Calendar.DATE);
        return day;
    }

    @ResponseBody
    @PostMapping("/exam_queryPaper")
    public ApiRest<List<Page<Paper>>> queryPaper(@RequestBody Paper paper){
//        Paper paper1 = paperService.queryPaperService(paper);
        LambdaQueryWrapper<Paper> queryWrapper1 = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Paper::getUserId,paper.getUserId());
        queryWrapper1.orderByDesc(Paper::getUserId);
        List<Paper> list = paperService.list(queryWrapper1);
        LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
        for(Paper paper1 : list){
            linkedHashSet.add(paper1.getUserId());
        }
        int num = 0;
        List<String> list2 = new ArrayList<>();
        List<Page<Paper>> page_Paper = null;
        for(String str : linkedHashSet){
            list2.add(str);
            num++;
        }
        for(int i = 0;i < num;i++){
            Page<Paper> page = new Page<>(0, 5);
            LambdaQueryWrapper<Paper> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(Paper::getUserId,list2.get(i));
            Page<Paper> page1 = paperService.page(page, queryWrapper2);
            page_Paper.add(page1);
            System.out.println(page_Paper);
        }

//        System.out.println(linkedHashSet);
//        return super.success(paper1);

        return super.success(page_Paper);
    }


}